<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="地理名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder=" 如：武汉市、襄阳市保康县马桥镇等"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="纬度，精确到小数点后6位" prop="latitude">
        <el-input
          v-model="queryParams.latitude"
          placeholder="请输入纬度，精确到小数点后6位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经度，精确到小数点后6位" prop="longitude">
        <el-input
          v-model="queryParams.longitude"
          placeholder="请输入经度，精确到小数点后6位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dash:locations:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dash:locations:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dash:locations:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dash:locations:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="locationsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="数据类型" align="center" prop="mapType" />
      <el-table-column label="地理名称" align="center" prop="name" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dash:locations:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dash:locations:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改地理位置信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <!-- 表单容器 -->
      <el-form ref="form" :model="form" :rules="rules"  class="location-form">
        <!-- 地图区域 -->
        <el-form-item>
          <div class="map-section">
            <el-alert
              title="提示：根据城市名称获取经纬度"
              type="info"
              show-icon
              :closable="false"
              class="map-alert"
            ></el-alert>
            <div class="map-container">
              <BaiduMap
                :showMap="true"
                :defaultCity="defaultCity"
                @city-selected="handleCitySelected"
                @search-error="handleSearchError"
                @map-load-error="handleMapLoadError"
              />
            </div>
          </div>
        </el-form-item>

        <!-- 表单内容区域 -->
        <div class="form-content">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="地图类型" prop="mapType">
                <el-select v-model="form.mapType" placeholder="请选择地图类型" class="form-input">
                  <el-option label="世界地图" value="world" class="map-type-option"></el-option>
                  <el-option label="中国地图" value="china" class="map-type-option"></el-option>
                  <el-option label="湖北地图" value="hubei" class="map-type-option"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地理位置名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入地理位置名称"
                  class="form-input"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="经度" prop="longitude">
                <el-input
                  v-model="form.longitude"
                  placeholder="请输入经度（保留6位小数）"
                  class="form-input"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度" prop="latitude">
                <el-input
                  v-model="form.latitude"
                  placeholder="请输入纬度（保留6位小数）"
                  class="form-input"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <!-- 对话框底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" class="btn-cancel">取消</el-button>
        <el-button type="primary" @click="submitForm" class="btn-submit">
          <i class="el-icon-check"></i> 确定保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLocations, getLocations, delLocations, addLocations, updateLocations } from "@/api/dash/locations"
import BaiduMap from "@/components/BaiduMap"
import { Backtop } from "element-ui";

export default {
  name: "Locations",
  components: {
    BaiduMap
  },
  data() {
    return {
       // 默认搜索城市，可以设置为空字符串不进行默认搜索
      defaultCity: '',
      // 存储从组件接收到的城市数据
      selectedCity: null,
      // 存储错误信息
      errorMessage: '',
      // 存储接收时间戳
      timestamp: '',

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 地理位置信息表格数据
      locationsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mapType: null,
        name: null,
        latitude: null,
        longitude: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mapType: [
          { required: true, message: "地图类型(世界地图、中国地图、湖北地图)不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "地理位置名称，如：武汉市、襄阳市保康县马桥镇等不能为空", trigger: "blur" }
        ],
        latitude: [
          { required: true, message: "纬度，精确到小数点后6位不能为空", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: "经度，精确到小数点后6位不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 处理城市选择成功事件 - 整合到handleCityFound中使用
    handleCitySelected(cityData) {
      console.log('收到城市数据:', cityData)
      // 调用现有的handleCityFound方法处理数据
      this.handleCityFound({ point: { lat: cityData.latitude, lng: cityData.longitude }, city: cityData.city || cityData.name });
    },

    // 处理搜索错误事件
    handleSearchError(errorData) {
      console.log('App组件收到错误:', errorData)
      this.errorMessage = `${errorData.name}: ${errorData.error}`
      this.selectedCity = null
    },
    /** 查询地理位置信息列表 */
    getList() {
      this.loading = true
      listLocations(this.queryParams).then(response => {
        this.locationsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        mapType: null,
        name: null,
        latitude: null,
        longitude: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加地理位置信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getLocations(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改地理位置信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLocations(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLocations(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除地理位置信息编号为"' + ids + '"的数据项？').then(function() {
        return delLocations(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dash/locations/export', {
        ...this.queryParams
      }, `locations_${new Date().getTime()}.xlsx`)
    },

    /** 处理城市查找结果，自动填充经纬度和地理名称 */
    handleCityFound(data) {
      if (data && data.point) {
        try {
          // 确保经纬度为有效数字并保留6位小数
          const latitude = parseFloat(data.point.lat);
          const longitude = parseFloat(data.point.lng);

          if (!isNaN(latitude) && !isNaN(longitude)) {
            // 自动填充经纬度到表单中，保留6位小数
            this.form.latitude = latitude.toFixed(6);
            this.form.longitude = longitude.toFixed(6);

            // 确保地理名称字段被正确赋值，优先使用城市名称
            if (data.city && typeof data.city === 'string') {
              this.form.name = data.city.trim();
            } else if (data.name && typeof data.name === 'string') {
              this.form.name = data.name.trim();
            }

            // 显示成功提示
            this.$message.success('已自动填充地理位置信息');

            // 打印日志以便调试
            console.log('位置信息已填充到表单:', {
              name: this.form.name,
              latitude: this.form.latitude,
              longitude: this.form.longitude
            });
          } else {
            this.$message.warning('获取的经纬度数据无效，请重新选择位置');
          }
        } catch (error) {
          console.error('填充位置信息时出错:', error);
          this.$message.error('处理位置信息失败，请重试');
        }
      } else {
        this.$message.warning('未获取到有效位置信息，请重新选择');
      }
    },

    /** 处理地图加载失败的情况 */
    handleMapLoadError(error) {
      this.$message.error('百度地图加载失败，请检查网络连接或API密钥配置');
      console.error('地图加载错误:', error);
    }
  }
}
</script>

<style scoped>
/* 弹出层表单样式 */
.location-form {
  padding: 0 0;
}

/* 地图区域样式 */
.map-section {
  margin-bottom: 25px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.map-section:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

/* 地图提示框样式 */
.map-alert {
  margin-bottom: 0;
  border-radius: 8px 8px 0 0;
  border: none;
  background-color: #ecf5ff;
  border-color: #d9ecff;

}

/* 地图容器样式 */
.map-container {
  height: 300px;
  background-color: #f5f5f5;
  border-radius: 0 0 8px 8px;
  overflow: hidden;
}

/* 表单内容区域样式 */
.form-content {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 表单输入框样式 */
.form-input {
  width: 100% !important;
  border-radius: 6px !important;
  transition: all 0.3s ease;
}

/* 控制弹出层高度 */
.location-form {
  max-height: 70vh; /* 限制表单容器最大高度为视口高度的70% */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}

/* 优化地图区域 */
.map-section {
  margin-bottom: 20px;
}

.map-container {
  max-height: 300px; /* 进一步限制地图容器高度 */
  overflow: hidden;
}

.form-content {
  padding: 0;
}

.form-input:focus {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1) !important;
}

/* 地图类型选项样式 */
.map-type-option {
  padding: 6px 0;
}

.map-type-option:hover {
  background-color: #ecf5ff;
}

/* 对话框底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px 20px;
  gap: 12px;
  background-color: #f8f9fa;
  border-radius: 0 0 8px 8px;
  margin: -20px -20px -20px -20px;
}

/* 按钮样式 */
.btn-cancel, .btn-submit {
  min-width: 80px;
  padding: 8px 20px;
  border-radius: 6px;
  transition: all 0.3s ease;
  font-size: 14px;
}

/* 提交按钮样式 */
.btn-submit {
  background-color: #409eff;
  border-color: #409eff;
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.btn-submit:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.btn-submit:active {
  transform: translateY(0);
}

/* 取消按钮样式 */
.btn-cancel {
  border-color: #dcdfe6;
}

.btn-cancel:hover {
  color: #606266;
  border-color: #c0c4cc;
  background-color: #f5f7fa;
}

/* 字数限制样式增强 */
.el-input__count {
  color: #909399;
  font-size: 12px;
}

.el-input__count.is-warning {
  color: #e6a23c;
}

/* 表单验证错误提示样式 */
.el-form-item__error {
  font-size: 12px;
  padding-top: 4px;
}

/* 对话框标题样式 */
.el-dialog__header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  padding: 15px 20px;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  padding: 12px 0;
}

.el-table td {
  padding: 10px 0;
  font-size: 13px;
}

/* 按钮组样式 */
.el-button {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-button:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 10px auto !important;
  }

  .el-dialog__body {
    padding: 15px;
  }

  .map-container {
    height: 250px;
  }

  .form-content {
    padding: 8px;
  }

  .dialog-footer {
    padding: 10px 15px;
    flex-direction: column;
  }

  .btn-cancel, .btn-submit {
    width: 100%;
    justify-content: center;
  }

  /* 移动设备上强制使用单列布局 */
  .el-row .el-col {
    width: 100% !important;
    max-width: 100% !important;
    flex: none;
  }
}

/* 打印样式优化 */
@media print {
  .el-dialog {
    width: 100% !important;
    height: 100% !important;
    box-shadow: none;
    margin: 0;
  }

  .dialog-footer {
    display: none;
  }
}
</style>
